<?php

class UserController extends Controller {

	/**
	 * @var string the default layout for the views. Defaults to
	 * '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout = '//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow',
				'actions'=>array('index', 'view'),
				'users'=>array('*'),
			),
			array('allow',
				'actions'=>array(
					'create',
					'update',
					'updatePassword',
					'role',
					'operation',
					'admin',
					'delete',
				),
				'users'=>array('@'),
			),
			array('deny', // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id) {
		if (Yii::app()->user->id != $id) {
			If (!Yii::app()->user->checkAccess('userView')) {
				$s = 'You are not authorized to perform this action.';
				throw new CHttpException(403, $s);
			}
		}

		$this->render('view', array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view'
	 * page.
	 */
	public function actionCreate() {
		If (!Yii::app()->user->checkAccess('userCreate')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		$model = new User;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['User'])) {
			$model->attributes = $_POST['User'];
			$model->username = strtolower($model->username);
			if ($model->validate()) {
				$model->salt = $model->generateSalt();
				$hashed = $model->hashPassword($model->password, $model->salt);
				$model->password = $hashed;
				$model->save(false);
				$this->redirect(array('view', 'id'=>$model->_id));
			}
		}

		$this->render('create', array('model'=>$model));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view'
	 * page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id) {
		if (Yii::app()->user->id != $id) {
			If (!Yii::app()->user->checkAccess('userUpdate')) {
				$s = 'You are not authorized to perform this action.';
				throw new CHttpException(403, $s);
			}
		}

		$model = $this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['User'])) {
			$model->attributes = $_POST['User'];
			$model->username = strtolower($model->username);
			if ($model->save()) {
				$this->redirect(array('view', 'id'=>$model->_id));
			}
		}

		$this->render('update', array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin'
	 * page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id) {
		If (!Yii::app()->user->checkAccess('userDelete')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		if (Yii::app()->request->isPostRequest) {
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we
			// should not redirect the browser
			if (!isset($_GET['ajax']))
					$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
				throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex() {
		If (!Yii::app()->user->checkAccess('userList')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		$dataProvider = new CActiveDataProvider('User');
		$this->render('index', array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin() {
		If (!Yii::app()->user->checkAccess('userManage')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		$model = new User('search');
		$model->unsetAttributes();  // clear any default values
		if (isset($_GET['User'])) $model->attributes = $_GET['User'];

		$this->render('admin', array(
			'model'=>$model,
		));
	}

	/**
	 * Update self password.
	 */
	public function actionUpdatePassword() {
		$model = new PasswordForm();

		if (isset($_POST['PasswordForm'])) {
			$model->attributes = $_POST['PasswordForm'];
			if ($model->validate()) {
				$user = $this->loadModel(Yii::app()->user->id);
				$hashed = $user->hashPassword($model->newPassword, $user->salt);
				$user->password = $hashed;
				$user->save(false);
				$this->redirect(array('view', 'id'=>$user->_id));
			}
		}
		/*
		  $model = $this->loadModel(Yii::app()->user->id);
		  $model->scenario = 'updatePassword';

		  if (isset($_POST['User'])) {
		  $model->attributes = $_POST['User'];
		  if ($model->validate()) {
		  $model->password = $_POST['User']['newPassword'];
		  $model->save(false);
		  $this->redirect(array('view', 'id'=>$model->_id));
		  }
		  }

		  $model->password = '';
		 */
		$this->render('updatePassword', array('model'=>$model));
	}

	/**
	 * Returns the data model based on the primary key given in the GET
	 * variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id) {
		$model = User::model()->findByPk((int) $id);
		if ($model === null)
				throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'user-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	/**
	 * Manage user roles.
	 *
	 * @param integer $id the ID of the model whose role to be managed
	 */
	public function actionRole($id) {
		if (Yii::app()->user->id != $id) {
			If (!Yii::app()->user->checkAccess('userRbac')) {
				$s = 'You are not authorized to perform this action.';
				throw new CHttpException(403, $s);
			}
		}

		if (isset($_POST['auth'])) {
			$auth = Yii::app()->authManager;
			if ($_POST['action'] == 'Revoke' && $_POST['auth'] == 'admin' &&
				$id == 1) {
				$s = 'You can not revoke admin role from admin user.';
				throw new CHttpException(403, $s);
			} else {
				if ($_POST['action'] == 'Assign') {
					$auth->assign($_POST['auth'], $id);
				} else {
					$auth->revoke($_POST['auth'], $id);
				}
			}
		}

		$data = array(
			'model'=>$this->loadModel($id),
		);
		$this->render('role', $data);
	}

	/**
	 * Manage user operation.
	 *
	 * @param integer $id the ID of the model whose operation to be managed
	 */
	public function actionOperation($id) {
		if (Yii::app()->user->id != $id) {
			If (!Yii::app()->user->checkAccess('userRbac')) {
				$s = 'You are not authorized to perform this action.';
				throw new CHttpException(403, $s);
			}
		}

		if (isset($_POST['auth'])) {
			$auth = Yii::app()->authManager;
			if ($_POST['action'] == 'Assign') {
				$auth->assign($_POST['auth'], $id);
			} else {
				$auth->revoke($_POST['auth'], $id);
			}
		}

		$data = array(
			'model'=>$this->loadModel($id),
		);
		$this->render('operation', $data);
	}

}
